package com.yansu.own.schedule.dingding;

import com.yansu.own.schedule.ArticleSynchronizationSchedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;
import java.util.concurrent.Callable;

public class SyncDingDingRunnable implements Callable<Integer> {

    public RedisTemplate redisTemplate;
    private int page;
    private int size;
    private ArticleSynchronizationSchedule task;

    private static final Logger log = LoggerFactory.getLogger(SyncDingDingRunnable.class);

    public SyncDingDingRunnable(RedisTemplate redisTemplate, ArticleSynchronizationSchedule task, int page, int size) {
        this.redisTemplate = redisTemplate;
        this.task = task;
        this.page = page;
        this.size = size;
    }

    @Override
    public Integer call() {
        int savedCount = 0;
        long start = System.currentTimeMillis();
        try {
            savedCount = task.saveDingDingArticle(page, size);
        } catch (Exception e) {
            log.info("第" + page + "页同步钉钉订阅号文章报错：", e);
        } finally {
            redisTemplate.opsForHash().increment(ArticleSynchronizationSchedule.SYNC_TYPE, "syncedCount", savedCount);
            redisTemplate.opsForHash().increment(ArticleSynchronizationSchedule.SYNC_TYPE, "syncedPage", 1);
            Map<Object, Object> syncHelper = redisTemplate.opsForHash().entries(ArticleSynchronizationSchedule.SYNC_TYPE);
            int result = (int) syncHelper.get("syncedCount");
            //耗时间隔
            long duration = (System.currentTimeMillis() - start);
            log.info("第" + page + "页同步钉钉订阅号文章数据量为：" + savedCount + " ,耗时:" + duration);
            log.info("当前已同步钉钉订阅号文章总数据量为:" + result);
            redisTemplate.opsForHash().increment(ArticleSynchronizationSchedule.SYNC_TYPE, "syncedTime", duration);
        }
        return savedCount;
    }

}
